package com.fanghuyun.iswaf.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ObjectSerializable {
	
	public static byte[] objectToBytes(Object obj) throws Exception{
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ObjectOutputStream sOut = new ObjectOutputStream(out);
        sOut.writeObject(obj);
        sOut.flush();
        byte[] bytes = out.toByteArray();
        return bytes;
    }
	
	public static Object bytesToObject(byte[] bytes) throws Exception{
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        ObjectInputStream sIn = new ObjectInputStream(in);
        return sIn.readObject();
    }
	
	public static void writeObject(Object obj,String path) throws Exception{
       File f=new File(path);
       if(f.exists()){
           f.delete();
       }
       FileOutputStream os=new FileOutputStream(f);
       ObjectOutputStream oos=new ObjectOutputStream(os);
       oos.writeObject(obj);
       oos.close();
       os.close();
    }

    public static Object readObject(File f) throws Exception{
       InputStream is=new FileInputStream(f);
       ObjectInputStream ois=new ObjectInputStream(is);
       return ois.readObject();
    }
    
}
